#!/usr/bin/python
# -*-coding:UTF-8 -*-

# ========================
# @Time  : 2020/6/2
# @Author: Sunny
# ========================

import json
import requests

from common.log_packaging import logger



class HttpRequest:
    """
    定义一个HTTP请求的类
    """

    def __init__(self):
        self.session = requests.Session()

    def __call__(self, method, url, data=None, json_flag=True, **kwargs):
        """
        实例()即可调用
        :param method: 请求方式
        :param url: 请求路径
        :param data: 请求数据
        :param json_flag: 请求数据格式，默认为json格式
        :param kwargs: 传递header和cookie等
        :return: 响应对象
        """
        method = method.lower()
        if isinstance(data, str):
            try:
                data = json.loads(data)  # 转换为字典类型
            except Exception as e:
                logger.exception(f"data不是json格式，无法转换为字典类型,异常信息是:{e}")
                data = eval(data)
                return data

        if method == "get":
            self.response = self.session.request(method, url, params=data, **kwargs)
        elif method == "post":
            if json_flag:
                self.response = self.session.request(method, url, json=data, **kwargs)  # json可以传递字典类型
            else:
                self.response = self.session.request(method, url, data=data, **kwargs)
        else:
            self.response = None
            logger.exception(f"不支持【{method}】的请求方法")
        return self.response


    def request_success(self, title, res, status_code=200):
        try:
            assert res.status_code == status_code
            logger.info(f"测试【{title}】发起请求成功！")
        except AssertionError:
            logger.exception(f"测试【{title}】发起请求失败！状态码为【{res.status_code}】")
            raise
        actual_res = json.loads(res.text, encoding="utf-8")
        return actual_res


    def assert_result(self, title, actual_res, expected_res):
        try:
            assert actual_res == expected_res
            logger.info(f"测试【{title}】通过\n")
        except AssertionError as err:
            logger.info(f"实际结果：{actual_res}")
            logger.info(f"期望结果：{expected_res}")
            logger.exception(f"测试【{title}】失败，异常信息：{err}\n")
            raise

    def close_session(self):
        """
        关闭request会话
        :return:
        """
        self.session.close()

if __name__ == '__main__':
    # oa_create_url = "http://192.168.96.73:8080/employees/search"
    # data = {"employee":{"empName":"米潇","folk":"4苗","officeArea":1,"department":{"departmentId":749},"departmentLevelId":749}}
    headers = {"userId":"15140","userName":"003464"}
    request_obj = HttpRequest()
    # response = request_obj("posT",oa_create_url,data,headers=headers)
    # print(response.text)
    # request_obj.close_session()
    url = "http://192.168.96.73:8080/asset/manage/stock/export"
    json_data = {"query":{"stateLock":"6","exportType":1}}
    r = request_obj('post', url=url, data=json_data, headers=headers, stream=True)
    print(type(r.raw.read()),r.raw.read())
    print(r.status_code)
    # print(resp.text)
    # with open("resp.txt", 'wb') as fd:
    #     for chunk in r.iter_content(chunk_size=218):
    #         fd.write(chunk)
